// 确保全局可访问
window.store = {
    state: {
        user: null,
        notifications: [],
        currentPage: 'dashboard',
        loading: false,
        useMockData: false  // 是否使用模拟数据
    },

    setUser(user) {
        this.state.user = user;
        localStorage.setItem('user', JSON.stringify(user));
    },

    setNotifications(notifications) {
        this.state.notifications = notifications;
    },

    setCurrentPage(page) {
        this.state.currentPage = page;
    },

    setLoading(loading) {
        this.state.loading = loading;
    },

    saveToStorage(key, data) {
        localStorage.setItem(key, JSON.stringify(data));
    },

    getFromStorage(key) {
        const data = localStorage.getItem(key);
        return data ? JSON.parse(data) : null;
    },

    clearStorage() {
        localStorage.removeItem('user');
        this.state.user = null;
        this.state.notifications = [];
    },

    async fetchData(url, options = {}) {
        try {
            this.setLoading(true);
            
            // 检查是否有模拟数据
            if (window.mockData) {
                // 根据URL返回模拟数据
                if (url === '/api/user/info') {
                    return window.mockData.user;
                } else if (url === '/api/notifications') {
                    return window.mockData.notifications;
                } else if (url === '/api/dashboard/data') {
                    return window.mockData.dashboard;
                }
            }
            
            // 如果没有模拟数据，则发起真实请求
            const response = await fetch(url, options);
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return await response.json();
        } catch (error) {
            console.error('获取数据失败:', error);
            return null;
        } finally {
            this.setLoading(false);
        }
    },

    getMockData(url) {
        // 根据URL返回相应的模拟数据
        if (url.includes('/api/user/info')) {
            return mockData.user;
        }
        if (url.includes('/api/dashboard/data')) {
            return mockData.dashboard;
        }
        if (url.includes('/api/alerts')) {
            return mockData.alerts;
        }
        if (url.includes('/api/events')) {
            return mockData.events;
        }
        return null;
    },

    init() {
        // 从本地存储加载用户信息
        const userStr = localStorage.getItem('user');
        if (userStr) {
            try {
                this.state.user = JSON.parse(userStr);
            } catch (e) {
                console.error('解析用户信息失败:', e);
                localStorage.removeItem('user');
            }
        }
        
        // 如果没有用户信息，使用模拟数据
        if (!this.state.user && window.mockData) {
            this.state.user = window.mockData.user;
        }
        
        // 使用模拟通知数据
        if (window.mockData) {
            this.state.notifications = window.mockData.notifications;
        }
    }
};

// 初始化存储
window.store.init(); 